package cn.e4j.core.quartz;

import cn.e4j.core.util.SpringContextHolder;
import cn.e4j.modular.system.entity.SysTask;
import cn.e4j.modular.system.service.SysTaskService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by yuan_rz on 2019-03-13.
 */
public abstract class AppJob implements Job {

    public abstract String getDescribe();
    public abstract String getDescribeOra();

    public abstract void logic(JobExecutionContext context,SysTask sysTask,Map<String,String> inDto);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        SysTaskService sysTaskService = SpringContextHolder.getBean("sysTaskService");
        Map<String,String> inDto = (HashMap<String,String>) context.getJobDetail().getJobDataMap().get(QuartzUtil.JOB_PARAM_KEY);
        SysTask sysTask = sysTaskService.getById(inDto.get("taskid"));
        try {
            this.logic(context,sysTask,inDto);
            //清空任务错误次数
            sysTask.setTASK004(0);
        } catch (Exception e) {
            //任务错误次数+1
            sysTask.setTASK004(sysTask.getTASK004() + 1);
            e.printStackTrace();
        } finally {
            //任务连续出错五次将自动停止
            try{
                if(sysTask.getTASK004() >= 5){
                    //QuartzUtil.pauseJob(sysTask, sysTask.getTASK_CLASS());
                    sysTaskService.stopTask(sysTask);
                }else{
                    sysTaskService.editData(sysTask);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
